package com.ccc.picture.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 图片裁剪工具类
 *
 * @author superC
 * @version 1.0.0
 * @date 2024/7/17
 */

public class ImageCutUtil {
    protected static final Logger logger = LoggerFactory.getLogger(ImageCutUtil.class);

    // 设置要裁剪的区域（左上角x坐标、y坐标）
    private static final int CROP_X = 0;
    private static final int CROP_Y = 0;

    private static final String OCTET_STREAM = "application/octet-stream;charset=UTF-8";

    public static void handle(MultipartFile file, int cutHeight, HttpServletResponse response) {

        try {
            String fileName = file.getOriginalFilename();
            logger.info("本次需要裁剪的高度为{}", cutHeight);
            logger.info("裁剪的图片名称为：{}", fileName);

            // 创建新的空白图像，大小为裁剪后的尺寸
            BufferedImage inputImage = ImageIO.read(file.getInputStream());
            logger.info("裁剪前，图片宽度为{}，图片高度为{}", inputImage.getWidth(), inputImage.getHeight());

            // 设置要裁剪的区域（宽度、高度）
            int cropWidth = inputImage.getWidth();
            int cropHeight = inputImage.getHeight() - cutHeight;
            logger.info("裁剪后，图片宽度为：" + cropWidth);
            logger.info("裁剪后，图片高度为：" + cropHeight);
            // 裁剪图像
            BufferedImage croppedImage = inputImage.getSubimage(CROP_X, CROP_Y, cropWidth, cropHeight);

            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            ImageIO.write(croppedImage, "png", response.getOutputStream());
            logger.info("图片裁剪完成 !");
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    public static void handleBatch(MultipartFile[] file, int cutHeight, HttpServletResponse response) {
        try {
            if (file.length == 0) {
                return;
            }
            logger.info("本次需要裁剪的高度为{}", cutHeight);
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            ZipOutputStream zipOutputStream = new ZipOutputStream(toClient);
            response.reset();
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setContentType(OCTET_STREAM);
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
            String fileName = "图片集(" + file.length + ")-" + cutHeight + ".zip";
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            for (MultipartFile inputFile : file) {
                String filename = Objects.requireNonNull(inputFile.getOriginalFilename());
                logger.info("裁剪的图片名称为：{}", filename);
                // 创建新的空白图像，大小为裁剪后的尺寸
                BufferedImage inputImage = ImageIO.read(inputFile.getInputStream());
                logger.info("裁剪前，图片宽度为{}，图片高度为{}", inputImage.getWidth(), inputImage.getHeight());

                // 设置要裁剪的区域（宽度、高度）
                int cropWidth = inputImage.getWidth();
                int cropHeight = inputImage.getHeight() - cutHeight;
                logger.info("裁剪后，图片宽度为{}，图片高度为{}", cropWidth, cropHeight);
                // 裁剪图像
                BufferedImage croppedImage = inputImage.getSubimage(CROP_X, CROP_Y, cropWidth, cropHeight);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(croppedImage, "png", baos);
                ZipEntry zipEntry = new ZipEntry(filename);
                zipOutputStream.putNextEntry(zipEntry);
                // 将内存流写入Zip文件
                zipOutputStream.write(baos.toByteArray());
            }
            zipOutputStream.closeEntry();
            zipOutputStream.flush();
            zipOutputStream.close();
        } catch (IOException e) {
            logger.error("【捕获异常-图片剪辑】\r\n异常记录：", e);
        }
    }

    public static void imageCut() {
        String inputImagePath = "D:\\ccc\\cccImg\\12.png";
        String outputImagePath = "D:\\ccc\\cccImg\\output.png";
        int cropX = 0;
        int cropY = 0;
        try {
            File inputFile = new File(inputImagePath);
            BufferedImage inputImage = ImageIO.read(inputFile);
            logger.info("裁剪前，图片宽度为：" + inputImage.getWidth());
            logger.info("裁剪前，图片高度为：" + inputImage.getHeight());
            int cropWidth = inputImage.getWidth();
            int cropHeight = inputImage.getHeight() - 200;
            logger.info("裁剪后，图片宽度为：" + cropWidth);
            logger.info("裁剪后，图片高度为：" + cropHeight);
            // 裁剪图像
            BufferedImage croppedImage = inputImage.getSubimage(cropX, cropY, cropWidth, cropHeight);
            // 保存裁剪后的图像
            File outputFile = new File(outputImagePath);
            ImageIO.write(croppedImage, "png", outputFile);
            logger.info("图片裁剪完成 !");
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

}
